import { fetchMirrorWebsite } from "@/spider/ipc";
import semver from "semver";

export const maven3Mirrors = {
  official: "https://dlcdn.apache.org/maven/maven-3/",
  tsinghua: "https://mirrors.tuna.tsinghua.edu.cn/apache/maven/maven-3/",
  tencent: "https://mirrors.cloud.tencent.com/apache/maven/maven-3/",
  huaweicloud: "https://mirrors.huaweicloud.com/apache/maven/maven-3/",
  aliyun: "https://mirrors.aliyun.com/apache/maven/maven-3/",
};

export async function getMavenVersions(): Promise<string[]> {
  try {
    return await Promise.any([
      getMavenVersions0(maven3Mirrors.tsinghua),
      getMavenVersions0(maven3Mirrors.tencent),
      getMavenVersions0(maven3Mirrors.official),
    ]);
  } catch (e: any) {
    console.log("get maven versions error", e);
    return [];
  }
}

export async function getMavenVersionsViaHuaweiCloud(): Promise<string[]> {
  try {
    return await getMavenVersions0(maven3Mirrors.huaweicloud);
  } catch (e: any) {
    console.log("get maven versions error", e);
    return [];
  }
}

async function getMavenVersions0(url: string): Promise<string[]> {
  let versions: string[] | null = null;
  try {
    let resp = await fetchMirrorWebsite(url);
    versions = resp.filter(it => /^\d+\..*$/.test(it.name)).map(it => it.name);
    versions.sort((a, b) => semver.compare(b, a));
  } catch (e: any) {
    console.log("get maven versions error", url, e);
  }
  if (versions != null && versions.length > 0) {
    return versions;
  }
  throw new Error("fetch failed for " + url);
}
